<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          size="mini"
          placeholder="请输入设备名称"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="sn号码" prop="sn" label-width="80px">
        <el-input
          size="mini"
          v-model="queryParams.sn"
          placeholder="请输入sn号码"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="mac地址" prop="mac" label-width="80px">
        <el-input
          v-model="queryParams.mac"
          size="mini"
          placeholder="请输入mac"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人设名称" prop="humanName" label-width="80px">
        <el-input
          v-model="queryParams.humanName"
          size="mini"
          placeholder="请输入人设名称"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绑定用户" prop="userName" label-width="80px">
        <el-input
          v-model="queryParams.userName"
          size="mini"
          placeholder="请输入绑定用户"
          clearable
          @clear="handleQuery"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:manage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['device:manage:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceInfoList">
      <el-table-column label="序号" type="index" fixed></el-table-column>
      <el-table-column label="设备名称" align="center" prop="name" width="180"/>

      <el-table-column label="秘钥" align="center" prop="authKey" width="300" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <i class="el-icon-document-copy" v-clipboard:copy="scope.row.authKey" v-clipboard:success="copyText" style="margin-right: 5px;cursor: pointer;"></i>
          {{ scope.row.authKey }}
        </template>
      </el-table-column>
      <el-table-column label="sn号" align="center" prop="sn" width="170"/>
      <el-table-column label="mac地址" align="center" prop="mac" width="170"/>
      <el-table-column label="设备状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <span v-show ="scope.row.status == 1"><el-tag type="info">在线</el-tag></span>
          <span v-show ="scope.row.status == 0"><el-tag type="success">离线</el-tag></span>
          <span v-show ="scope.row.status == 2"><el-tag type="success">激活完成</el-tag></span>
          <span v-show ="scope.row.status == 3"><el-tag type="success">待激活</el-tag></span>
        </template>
      </el-table-column>
      <el-table-column label="激活时间" align="center" prop="activateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activateTime)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="绑定客户" align="center" prop="userName" width="130"/>
      <el-table-column label="模型名称" align="center" prop="aiModelName" width="140"/>
      <el-table-column label="人设名称" align="center" prop="humanName" width="200"/>
      <el-table-column label="日志状态" align="center" prop="isUploadLog" width="140">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isUploadLog"
            :active-value="1"
            :inactive-value="0"
            disabled
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:manage:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:manage:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="updateConfigStatus(scope.row)"
            v-hasPermi="['device:manage:updateAuthStatus']"
          >
            <span v-show="scope.row.isUploadLog == 1">暂停上报</span>
            <span v-if="scope.row.isUploadLog == 0">上报日志</span>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="11" v-show="this.form.uid != null">
            <el-form-item label="设备uid:" label-width="110px">
              <span>{{this.form.uid}}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="应用名称:" prop="name" label-width="110px">
              <el-input v-model="form.name" placeholder="请输入应用名称" />
            </el-form-item>
          </el-col>
          <el-col :span=11>
            <span style="margin-left: 140px">
              <el-button type="primary" @click="submitForm" >保存</el-button>
            </span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=11>
            <el-form-item label="mac地址:" prop="mac" label-width="110px">
              <el-input v-model="form.mac" placeholder="请输入mac地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=11>
            <el-form-item label="sn号:" prop="sn" label-width="110px">
              <el-input v-model="form.sn" placeholder="请输入sn号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span=11>
            <el-form-item label="大模型:" prop="modelAppUid" label-width="110px">
              <el-select v-model="form.modelAppUid" placeholder="请选择">
                <el-option
                  v-for="item in this.modelAppInfoDtoList"
                  :key="item.uid"
                  :label="item.name"
                  :value="item.uid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="绑定客户:" prop="name" label-width="110px">
              <el-input v-model="form.userName" placeholder="绑定客户名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="aiui:" prop="modelAppUid" label-width="110px">
              <el-select v-model="form.aiuiUid" placeholder="请选择">
                <el-option
                  v-for="item in this.aiUiConfigDtoList"
                  :key="item.uid"
                  :label="item.name"
                  :value="item.uid">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="4">
          <el-form-item label="人设:" prop="name">
            <div v-for="(item, index) in this.humanModelManagerDtoList">
              <!--左边-->
              <el-col :span="12" v-show="index % 2 == 0">
                <el-card class="box-card">
                  <el-row>
                    <el-col :span="3">
                      <el-avatar  :src="item.logoUrl"></el-avatar>
                    </el-col>
                    <el-col :span="14">
                      {{item.name}}
                    </el-col>
                    <el-col :span="7">
                      <el-radio v-model="form.humanCharacterUid" :label="item.uid" border>默认</el-radio>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="17">
                      <el-col :span="5">
                        <span>授权时间：</span>
                      </el-col>
                      <el-col :span="10">
                        <el-date-picker
                          disabled
                          class="auth_date"
                          size="mini"
                          v-model="value2"
                          type="datetimerange"
                          :picker-options="pickerOptions"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          align="right">
                        </el-date-picker>
                      </el-col>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
              <!--右边-->
              <el-col :span="12" v-show="index % 2 == 1">
                <el-card class="box-card">
                  <el-row>
                    <el-col :span="3">
                      <el-avatar  :src="item.logoUrl"></el-avatar>
                    </el-col>
                    <el-col :span="14">
                      {{item.name}}
                    </el-col>
                    <el-col :span="7">
                      <el-radio v-model="form.humanCharacterUid" :label="item.uid" border>默认</el-radio>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="17">
                      <el-col :span="5">
                        <span>授权时间：</span>
                      </el-col>
                      <el-col :span="10">
                        <el-date-picker
                          disabled
                          class="auth_date"
                          size="mini"
                          v-model="value2"
                          type="datetimerange"
                          :picker-options="pickerOptions"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          align="right">
                        </el-date-picker>
                      </el-col>
                    </el-col>
                  </el-row>
                </el-card>
              </el-col>
            </div>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 芯片导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDeviceInfo, updateDeviceInfoLogStatus, selectDeviceInfo,updateDeviceInfo, insertDeviceInfo, deleteDeviceInfoList} from "@/api/platform/device/manage/manage";
import {selectTenantAuthAiByTenantUid} from "@/api/tenant/ai/config";
import { getToken } from "@/utils/auth";

export default {
  name: "DeviceLog",
  data() {
    return {
      tenantAiConfig: {},
      operationType: true,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      modelAppInfoDtoList: [],
      humanModelManagerDtoList: [],
      aiUiConfigDtoList: [],
      deviceInfoList: [],
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      detailOpen: false,
      // 是否显示添加修改弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 文件导入参数
      upload: {
        // 是否显示弹出层（链接导入）
        open: false,
        // 弹出层标题（链接导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/device/deviceInfo/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        mac: [
          { required: true, message: "mac不能为空", trigger: "blur" }
        ],
        sn: [
          { required: true, message: "sn不能为空", trigger: "blur" }
        ],
        modelAppUid: [
          { required: true, message: "大模型必须选择", trigger: "blur" }
        ],
        humanCharacterUid: [
          { required: true, message: "人设必须选择", trigger: "blur" }
        ],
        aiuiUid: [
          { required: true, message: "aiui必须选择", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询模板列表 */
    getList() {
      this.loading = true;
      listDeviceInfo(this.queryParams).then(response => {
        this.deviceInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    copyText(){
      this.$message.success("复制成功")
    },
    //修改配置状态
    updateConfigStatus(row){
      let message = ""
      let data = {};
      data.isUploadLog = row.isUploadLog;
      data.uid = row.uid
      if(data.isUploadLog == 0){
        message = "<div>确定要启动日志上报: <span>&nbsp;&nbsp;&nbsp;" + row.name + " ?</span></div>"+
          "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + row.uid
      }else{
        message = "<div>确定要暂停日志上报: <span>" + row.name + " ?</span></div>"+
          "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + row.uid
      }
      this.$modal.confirm(message).then(function() {
        return updateDeviceInfoLogStatus(data);
      }).then(() => {
        if (row.isUploadLog == 0) {
          this.$modal.msgSuccess("已启用");
        } else {
          this.$modal.msgSuccess("已停用");
        }
        this.getList();
      }).catch(() => {});
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    selectAuthAiByTenantUid(){
      selectTenantAuthAiByTenantUid().then(response =>{
        this.tenantAiConfig = response.data;
        this.modelAppInfoDtoList = this.tenantAiConfig.modelAppInfoDtoList;
        this.humanModelManagerDtoList = this.tenantAiConfig.humanModelManagerDtoList;
        this.aiUiConfigDtoList = this.tenantAiConfig.aiUiConfigDtoList;
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增设备";
      this.selectAuthAiByTenantUid()
    },
    //修改按钮
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改设备";
      this.selectAuthAiByTenantUid()
      selectDeviceInfo(row.uid).then(response =>{
        this.form = response.data;
      })
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "设备导入";
      this.upload.open = true;
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.humanCharacterUid == undefined || this.form.humanCharacterUid == null){
            this.$modal.msgWarning("请选择人设");
            return
          }
          if (this.form.uid == undefined) {
            let data = this.form
            const message = "<div>确定要新增设备信息？</div>"
            this.$modal.confirm(message).then(function() {
              return insertDeviceInfo(data);
            }).then(() => {
              this.reset()
              this.$modal.msgSuccess("修改成功");
              this.open=false;
              this.getList();
            })
          }else{
            let data = this.form;
            //提示
            const message = "<div>确定要修改应用信息？</div>"
            this.$modal.confirm(message).then(function() {
              return updateDeviceInfo(data);
            }).then(() => {
              this.reset()
              this.$modal.msgSuccess("修改成功");
              this.open=false;
              this.getList();
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      let data = {
        uidList: []
      };
      data.uidList.push(row.uid)
      //提示
      const message = "<div>确定要删除应用: <span>" + row.name + " ?</span></div>"+
        "<span style='margin-top: 20px'>应用ID:</span> &nbsp;&nbsp;&nbsp;" + row.uid
      this.$modal.confirm(message).then(function() {
        return deleteDeviceInfoList(data);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList()
      })
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('device/deviceInfo/getImportTemplate', {
      }, `deviceInfo_template_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
<style scoped>
.auth_date{
  width:240px
}
.box-card{
  background: rgba(0,0,0,0.04);
}

.box-card:hover{
  cursor: pointer;
  background: rgba(0,0,0,0.06);
}
</style>
